package handler

import (
	"iptv_server/v3/src/settings"
	"iptv_server/v3/v2_src/bili_live"
	"iptv_server/v3/v2_src/douyu_live"
	"iptv_server/v3/v2_src/handler/middleware"
	"iptv_server/v3/v2_src/huya_live"
	"iptv_server/v3/v2_src/utils"
	"net/http"
	"strconv"
	"strings"
)

var (
	noTV string = settings.SiteDomain + "/files/videos/noTv.mp4"
)

func initLive(mux *http.ServeMux, middles ...middleware.MiddleWare) {
	h := middleware.ApplyMiddles(&Live{}, middles...)
	mux.Handle("/api/live/", h)

	if noTV1 := settings.GetNoTv(); len(noTV1) > 10 {
		//
		noTV = noTV1
	}

}

type Live struct {
}

// "/api/live/"
// "0:/1:api/2:live/3:/4:"
func (l *Live) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	ps := strings.Split(r.URL.Path, "/")

	if len(ps) <= 2 {
		return
	}

	// len ==3
	site := strings.ToLower(ps[3])
	// roomid, err := strconv.Atoi(ps[4],10)
	if len(ps) == 4 {
		//todo
		return
	}
	roomid, err := strconv.ParseInt(ps[4], 10, 64)
	if err == nil {
		url := ""
		if site == "douyu" {
			url = douyu_live.GetOne(roomid)
		} else if site == "bilibili" || site == "bili" {
			url = bili_live.GetOne(roomid)
		} else if site == "huya" {
			url = huya_live.GetOne(roomid)
		}

		utils.Logger.Debugf("result:url= %v\n", url)
		// w.Header().
		if utils.IsHttpUrl(url) {
			// w.WriteString(url)
		} else {
			url = noTV
		}
		http.Redirect(w, r, url, http.StatusFound)
	}

}

/*
curl http://localhost:9966/api/live/bili/833792
curl http://localhost:9966/api/live/bilibili/833792
curl http://localhost:9966/api/live/douyu/338759
url := bili_live.GetVideoUrl(833792)
fmt.Printf("url: %v\n", url)
url2 := douyu_live.GetVideoUrl(338759)
fmt.Printf("url2: %v\n", url2)
*/
